package com.lmx.repoDomain.repository;

import com.lmx.common.constants.CommonConstants;
import com.lmx.persistence.service.NursingService;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.NurseMerch;
import io.katharsis.queryParams.QueryParams;
import io.katharsis.repository.annotations.JsonApiFindAll;
import io.katharsis.repository.annotations.JsonApiResourceRepository;
import io.katharsis.repository.annotations.JsonApiSave;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;

@JsonApiResourceRepository(NurseMerch.class)
@Component
public class NurseMerchRepository extends BaseRepository<NurseMerch> {

	@Autowired
	private NursingService nursingService;

	@PostConstruct
	public void init() {
		dslJpaService.setEntityClass(NurseMerch.class);
	}

	@Override
	@JsonApiSave
	public NurseMerch save(NurseMerch model) {
		if (model.getId() == null) {
			NurseMerch temp = nursingService.getNurseMerchByCode(model);
			if (temp != null) {
				model.setErrcode(4);// 名字重复
				throw new BusinessException(null, CommonConstants.ERROR_CODE.NAME_ERROR.label(), null);
			}
			model = super.save(model);
		} else {
			if (model.getDelStatus() == 1) {// 删除
				// 判断删除
				int deleteFlag = nursingService.checkNurseMerchRelations(model);
				if (deleteFlag > 0) {
					model.setErrcode(8);// no delete
					throw new BusinessException(null, CommonConstants.ERROR_CODE.NO_DELETE.label(), null);
				}
				dslJpaService.update(model);
			} else {
				// 修改NurseMerch信息 验证code
				NurseMerch temp = nursingService.getNurseMerchByCodeFilterId(model);
				if (temp == null) {
					dslJpaService.update(model);
				} else {
					model.setErrcode(4);// 名字重复
					throw new BusinessException(null, CommonConstants.ERROR_CODE.NAME_ERROR.label(), null);
				}
			}
		}
		return model;
	}
	
	@Override
	@JsonApiFindAll
	public Iterable<NurseMerch> findAll(final QueryParams requestParams) {
		List<NurseMerch> listData=new ArrayList<>();
		listData=(List<NurseMerch>) super.findAll(requestParams);
        return listData;
	}

}
